package com.cy.store.controller;

import com.cy.store.controller.ex.FileException;
import com.cy.store.entity.User;
import com.cy.store.service.UserService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//@Controller
@RestController //作用 = @Controller + @ResponseBody
@RequestMapping("users")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;

//    @RequestMapping("reg")
//    @ResponseBody   //表示该方法的响应结果以json格式进行数据的响应给前端
//    public JsonResult<Void> reg(User user){
//        JsonResult<Void> result = new JsonResult<>();
//        try {
//            userService.reg(user);
//            result.setState(200);
//            result.setMessage("用户注册成功");
//        } catch (UsernameDuplicatedException e) {
//            result.setState(4000);
//            result.setMessage("用户名被占用");
//        } catch (InsertException e) {
//            result.setState(5000);
//            result.setMessage("注册时产生未知异常");
//        }
//        return result;
//    }

    /**
     * 后端采用对象来接受前端的数据，springboot约定大于配置
     * 1、请求处理方法的参数列表设置为pojo类型来接受前端的数据
     *   springboot会将前端url地址中的参数名和pojo类的属性名进行比较，如果这两个的名称相同，则将值注入到对应的pojo类型上
     * @param user
     * @return
     */
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return  new JsonResult<>(OK);
    }

    /**
     * 2、请求处理方法的参数列表设置为非pojo类型，
     * springboot会直接将请求的参数名和方法的参数名直接比较，如果名称相同则自动完成值的依赖注入
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User user = userService.login(username,password);
        //向session对象中完成数据的绑定
        session.setAttribute("uid",user.getUid());
        session.setAttribute("username",user.getUsername());
        session.setAttribute("avatar",user.getAvatar());
//        System.out.println(user);
//        System.out.println("uname= "+getUsernameFromSession(session));
//        System.out.println("uid = "+getUidFromSession(session));
        return  new JsonResult<User>(OK,user);
    }

    @RequestMapping("changePassword")
    public JsonResult<Void> changePassword(String oldPassword, String newPassword,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    @RequestMapping("findByUid")
    public  JsonResult<User> findByUid(HttpSession session){
        User user = userService.findByUid(getUidFromSession(session));
        return new JsonResult<>(OK,user);
    }

    @RequestMapping("changeInfo")
    public JsonResult<Void> changeInfo(User user,HttpSession session){
        Integer uid = getUidFromSession(session);
        String userName = getUsernameFromSession(session);
//        User user =new User();
//        user.setPhone(phone);
//        user.setEmail(email);
//        user.setGender(gender);
        userService.changeInfo(uid,userName,user);
        return new JsonResult<>(OK);
    }

    /** 10*1024*1024B */
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;

    /** 限制上传文件的类型  */
    public static final List<String> AVATAR_TYPE = new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");

    }

    /**
     * @RequestParam("file") 是请求中的参数注入到方法的参数中
     * @param session
     * @param file
     * @return
     */
    @RequestMapping("changeAvatar")
    public JsonResult<String> changeAvatar(HttpSession session, @RequestParam("file") MultipartFile file){
        // 判断文件是否非空
        if(file.isEmpty()) throw new FileException("文件为空");
        // 看文件大小是否超出限制
        if(file.getSize() > AVATAR_MAX_SIZE) throw new FileException("文件大小超出限制");
        // 判断文件类型
        String  contentType = file.getContentType();
        if(!AVATAR_TYPE.contains(contentType)) throw new FileException("文件类型不支持");

        // 上传文件
        String parent = session.getServletContext().getRealPath("upload");
        File dir = new File(parent);
        if(!dir.exists()) dir.mkdirs();
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase()+suffix;
        File dest = new File(dir,filename); //空文件
        try {
            // 将file输入到dest
            file.transferTo(dest);
        } catch (IOException e) {
            throw new FileException("文件读写异常");
        }

        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        String avatar = "/upload/"+filename;
        userService.changeAvatar(uid,username,avatar);
        return new JsonResult<>(OK,avatar);
    }
}
